// app.ts
import {
    login,
    userDetail,
    commonTagList,
    getCodeRegion,
    heartbeat,
    friendRequestList,
} from "./utils/api.js";
import SDK from "./sdk/Easemob-chat-4.9.1.js";

App({
    globalData: {
        userId: "",
        token: "",
        hasMobile: false,
        profileFrom: "",
        mbtiList: [
            "INTP",
            "INTJ",
            "ENTJ",
            "ENTP",
            "ENFP",
            "INFP",
            "ENFJ",
            "INFJ",
            "ISTJ",
            "ISFJ",
            "ESTJ",
            "ESFJ",
            "ISTP",
            "ISFP",
            "ESTP",
            "ESFP",
        ],
        langList: [
            {
                text: "普通话",
                value: "zh_CN",
            },
            {
                text: "英语",
                value: "en_US",
            },
        ],
        langList1: [
            {
                text: "普通话",
                value: "zh_CN",
            },
            {
                text: "英语",
                value: "en_US",
            },
        ],
        loginInfo: {
            completedStep: 0,
        },
        userInfo: {},
        timer: null,
        timerIm: null,
        navBarHeight: 0, // 导航栏高度
        totalUnread: 0,
    },
    watch: function (key: any, okey: any, method: any) {
        // this.globalData里面的对象
        if (okey) {
            var obj = this.globalData[okey];
        } else {
            var obj = this.globalData;
        }
        //加个前缀生成隐藏变量，防止死循环发生
        let ori = obj[key]; //obj[key]这个不能放在Object.defineProperty里
        if (ori) {
            //处理已经声明的变量，绑定处理
            method(ori);
        }
        Object.defineProperty(obj, key, {
            configurable: true,
            enumerable: true,
            set: function (value) {
                this["_" + key] = value;
                method(value);
            },
            get: function () {
                // 在其他界面调用key值的时候，这里就会执行。
                if (typeof this["_" + key] == "undefined") {
                    if (ori) {
                        //这里读取数据的时候隐藏变量和 globalData设置不一样，所以要做同步处理
                        this["_" + key] = ori;
                        return ori;
                    } else {
                        return undefined;
                    }
                } else {
                    return this["_" + key];
                }
            },
        });
    },
    onShow() {},
    /**
     * 获取导航栏高度
     */
    getNavBarHeight() {
        // const systemInfo = wx.getSystemInfoSync()
        // const navBarHeight = systemInfo.statusBarHeight + 44 // 44 是导航栏的高度（不包括状态栏）
        // console.log(navBarHeight);
        // this.globalData.navBarHeight = navBarHeight || 95
        const systemInfo = wx.getSystemInfoSync();
        const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
        const navBarHeight =
            menuButtonInfo.top +
            menuButtonInfo.height +
            (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 -
            3;
        this.globalData.navBarHeight = navBarHeight || 95;
    },
    onLaunch() {
        wx.onNetworkStatusChange((res) => {
            let msg = "";
            if (!res.isConnected) {
                msg = "当前网络不可用，请检查你的网络设置";
            } else if (res.networkType === "none") {
                msg = "网络开小差了,请网络良好后重试";
            }
            if (msg) {
                wx.showToast({
                    title: msg,
                    icon: "none",
                });
                return false;
            }
        });
        this.getNavBarHeight();
        // 展示本地存储能力
        const logs = wx.getStorageSync("logs") || [];
        logs.unshift(Date.now());
        wx.setStorageSync("logs", logs);
        const loginInfo = wx.getStorageSync("loginInfo");
        const interestList = wx.getStorageSync("interestList");
        const professionList = wx.getStorageSync("professionList");
        let token = this.globalData.token;
        if (loginInfo && Object.keys(loginInfo).length > 0) {
            token = this.globalData.token || loginInfo.token;
            this.initIm();
        }
        // that.globalData.loginInfo
        // 如果没登录，则登录
        // if (!token) {
        //   this.getLogin()
        // } else {
        //   const loginInfo = wx.getStorageSync('loginInfo')
        //   if (this.globalData.loginInfo.completedStep != loginInfo.completedStep) {
        //     this.getLogin()
        //   }
        // }

        if (!interestList || interestList.length <= 0) {
            this.getInterest();
        }
        if (!professionList || professionList.length <= 0) {
            this.getProfession();
        }
        // 判断缓存中是否有区域数据，如果没有，就重新请求数据
        const areaRegion = wx.getStorageSync("areaRegion");

        if (!areaRegion || areaRegion.length < 0) {
            this.getRegionList();
        }
        // 每分钟请求一次
        if (this.globalData.timer) {
            clearInterval(this.globalData.timer);
        }
        this.globalData.timer = setInterval(() => {
            this.getHeartbeat();
            this.queryImData();
        }, 30000);

        if (this.globalData.timerIm) {
            clearInterval(this.globalData.timerIm);
        }
        this.globalData.timerIm = setInterval(() => {
            this.queryImData();
        }, 10000);
    },
    queryImData() {
        const that = this;
        let wxIm = wx.conn;
        // 判断是否IM连接成功
        if (wxIm) {
            // 此处表示已查到im,就停止
            return;
        } else {
            // 如果没有wx.im，说明im还没连接成功，就再次调用getImData方法继续查
            setTimeout(() => {
                const loginInfo = wx.getStorageSync("loginInfo");
                if (loginInfo && Object.keys(loginInfo).length > 0) {
                    that.initIm();
                }
            }, 2000);
        }
    },
    /**
     * 接入IM环信
     */
    initIm() {
        const loginInfo = wx.getStorageSync("loginInfo");
        const userInfo = wx.getStorageSync("userInfo");
        const that = this;
        //实例化SDK对象
        const WebIM: any = (wx.WebIM = SDK);
        wx.conn = new WebIM.connection({
            appKey: "1120241122157763#frieneedtest",
            https: true, //是否使用HTTPS
            url: "wss://im-api-wechat.easemob.com/websocket", // socket server (3.0 SDK)
            apiUrl: "https://a1.easemob.com", // rest server
            heartBeatWait: 30000, //心跳间隔
            autoReconnectNumMax: 5, //自动重连次数
            useOwnUploadFun: true, // 是否使用自己的上传函数，如想把图片、文件上传到自己的服务器。
            delivery: true,
        });
        wx.conn
            .open({
                user: userInfo.userId || this.globalData.userId,
                accessToken: loginInfo.imUserToken,
            })
            .then(() => {
                return true;
            })
            .catch((reason: any) => {});

        wx.conn.addEventHandler("connectionListener", {
            onConnected: () => {
                console.log("连接成功");
                // that.getFriendAddMsg()
                this.listenChannel();
            },
            // 自 4.8.0 版本，`onDisconnected` 事件新增断开原因回调参数, 告知用户触发 `onDisconnected` 的原因。
            onDisconnected: () => {
                console.log("连接断开");
            },
            onReconnecting: () => {
                console.log("重连中");
            },
            // 当前用户收到好友请求。用户 B 向用户 A 发送好友请求，用户 A 收到该事件。
            onContactInvited: function (msg: any) {
                console.log(msg, 1111111);
            },
            // 当前用户被其他用户从联系人列表上移除。用户 B 将用户 A 从联系人列表上删除，用户 A 收到该事件。
            onContactDeleted: function (msg: any) {
                console.log(msg, 2222222);
            },
            // 当前用户新增了联系人。用户 B 向用户 A 发送好友请求，用户 A 同意该请求，用户 A 收到该事件，而用户 B 收到 `onContactAgreed` 事件。
            onContactAdded: function (msg: any) {
                console.log(msg, 3333333);
            },
            // 当前用户发送的好友请求被拒绝。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，拒绝加好友，则用户 A 收到该事件。
            onContactRefuse: function (msg: any) {
                console.log(msg, 444444);
            },
            // 当前用户发送的好友请求经过了对方同意。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，同意加好友，则用户 A 收到该事件。
            onContactAgreed: function (msg: any) {
                console.log(msg, 555555);
            },
        });
    },
    listenChannel() {
        this.getTotalUnreadCount();
        wx.conn.listen({
            onReceivedMessage: (message: any) => {
                // 处理接收到的所有消息
                setTimeout(() => {
                    this.getTotalUnreadCount();
                }, 500);
            },
            onReadMessage: (message) => {
                setTimeout(() => {
                    this.getTotalUnreadCount();
                }, 500);
            },
            onGroupEvent: (message: any) => {
                // 处理接收到的所有消息
                setTimeout(() => {
                    this.getTotalUnreadCount();
                }, 500);
            },
        });
    },
    getTotalUnreadCount() {
        const params = {
            pageSize: 50, // pageSize: 每页期望获取的会话数量。取值范围为 [1,50]，默认为 `20`。
            cursor: "",
        };
        wx.conn.getServerConversations(params).then((res: any) => {
            const { conversations, cursor } = res.data;
            let totalUnread = 0;
            if (conversations && conversations.length) {
                conversations.map((item: any) => {
                    item.userId = item.conversationId;
                    if (item.conversationType == "singleChat") {
                        totalUnread += item.unReadCount || 0;
                    }
                });
            }
            this.globalData.totalUnread = totalUnread;
            console.log(totalUnread);
            this.updateTabBar(totalUnread);
            this.getFriendRequestList(totalUnread);
        });
    },
    getFriendRequestList(totalUnread: number) {
        friendRequestList({}).then((res: any) => {
            const num = res.length || 0;
            this.globalData.totalUnread = totalUnread + num;
            this.updateTabBar(this.globalData.totalUnread);
        });
    },
    updateTabBar(unreadCount: number) {
        console.log("====================================");
        console.log(getCurrentPages());
        console.log(unreadCount);
        console.log("====================================");
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage && currentPage.getTabBar) {
            const tabBar = currentPage.getTabBar();
            if (tabBar) {
                tabBar.setData({
                    unReadCount: unreadCount,
                });
            }
        }
    },
    loginMobileFlase() {
        this.globalData.hasMobile = false;
    },
    /**
     * 获取好友申请列表
     */
    getFriendAddMsg() {
        wx.conn.addEventHandler("contactEvent", {
            // 当前用户收到好友请求。用户 B 向用户 A 发送好友请求，用户 A 收到该事件。
            onContactInvited: function (msg: any) {
                console.log(msg, 1111111);
            },
            // 当前用户被其他用户从联系人列表上移除。用户 B 将用户 A 从联系人列表上删除，用户 A 收到该事件。
            onContactDeleted: function (msg: any) {
                console.log(msg, 2222222);
            },
            // 当前用户新增了联系人。用户 B 向用户 A 发送好友请求，用户 A 同意该请求，用户 A 收到该事件，而用户 B 收到 `onContactAgreed` 事件。
            onContactAdded: function (msg: any) {
                console.log(msg, 3333333);
            },
            // 当前用户发送的好友请求被拒绝。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，拒绝加好友，则用户 A 收到该事件。
            onContactRefuse: function (msg: any) {
                console.log(msg, 444444);
            },
            // 当前用户发送的好友请求经过了对方同意。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，同意加好友，则用户 A 收到该事件。
            onContactAgreed: function (msg: any) {
                console.log(msg, 555555);
            },
        });
    },
    /**
     * 登录
     */
    getLogin() {
        const that = this;
        wx.login({
            success(res1) {
                if (res1.code) {
                    // 调用登录的接口
                    const params = {
                        code: res1.code,
                    };
                    login(params).then((res: any) => {
                        wx.showToast({
                            title: "登录成功",
                        });
                        const { header, data } = res;
                        let loginInfo = data.data;
                        let token =
                            header["Frieneed-Mini-Program-Satoken"] ||
                            header["frieneed-mini-program-satoken"];
                        let key =
                            header["Access-Control-Expose-Headers"] ||
                            header["access-control-expose-headers"]; // 用户的token放在response里面返回的
                        let obj = {
                            token,
                            key,
                            ...loginInfo,
                        };

                        that.globalData.token = token;
                        that.globalData.loginInfo = loginInfo;
                        that.globalData.hasMobile = loginInfo.hasMobile;
                        wx.setStorage({
                            key: "loginInfo",
                            data: obj,
                            success() {
                                that.getUserInfo();
                            },
                        });
                        return true;
                    });
                } else {
                    wx.showToast({
                        title: "网络异常",
                        icon: "none",
                    });
                }
            },
        });
    },
    /**
     * 获取用户详情
     */
    getUserInfo() {
        const params = {};
        const that = this;
        userDetail(params).then((res) => {
            this.globalData.userId = res.userId;
            this.globalData.userInfo = res;
            wx.setStorage({
                key: "userInfo",
                data: res,
                success() {
                    that.initIm();
                },
            });
        });
    },
    /**
     * 获取兴趣列表
     */
    getInterest() {
        let params = {
            tagType: "INTEREST",
        };
        commonTagList(params).then((res) => {
            res.length > 0 &&
                res.map((item: any) => {
                    item.text = item.tagName;
                    item.selectFlag = false;
                });
            wx.setStorage({
                key: "interestList",
                data: res,
            });
        });
    },
    /**
     * 获取职业技能列表
     */
    getProfession() {
        let params = {
            tagType: "SKILL",
        };
        commonTagList(params).then((res) => {
            let list: any = [];
            res.length > 0 &&
                res.map((item: any) => {
                    item.text = item.tagName;
                    item.selectFlag = false;
                    item.value = item.tagTypeId;
                    list.push(item);
                });

            wx.setStorage({
                key: "professionList",
                data: list,
            });
        });
    },
    // 获取区域
    getRegionList() {
        // type， 是用来判断是获取省还是市还是区
        getCodeRegion({}).then((res: any) => {
            wx.setStorageSync("areaRegion", res);
        });
    },
    getHeartbeat() {
        heartbeat({}).then((res) => {});
    },
});
